package com.xit.cloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @author malguy-wang sir
 * @create ---
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());//填入自定义的实现类
    }

    @Autowired //注入数据源
    private DataSource dataSource;

    //注册自动登录需要的类
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
//        jdbcTokenRepository.setCreateTableOnStartup(true); //自动创建表,但是我们已经创建了就不需要
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

    //注册编码器,不注册会报错
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置退出后跳转的页面,路径随意填
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/logout").permitAll();
        //设置无权限访问时显示的页面
        http.exceptionHandling().accessDeniedPage("/static/unauth.html");
        http.formLogin() //自定义登录页面
                .loginPage("/login.html") //跳转到自己的登录页面,只能是接口
                .loginProcessingUrl("/user/login")  //登录访问路径(表单提交到哪个controller),security会自动处理
                .defaultSuccessUrl("/test/index").permitAll() //登录成功后跳转到哪
                .and().authorizeRequests() //哪些需要认证才能访问,哪些不需要
                .antMatchers("/","/user/insert","/user/i","/user/zc","/user/login", "/hello").permitAll() //访问这些路径的时候不需要认证
                .anyRequest().authenticated() //表示其他所有请求都需要认证
                .and().rememberMe().tokenRepository(persistentTokenRepository()) //开启自动登录功能
                .tokenValiditySeconds(60 * 60 * 24) //设置token有效市场,单位秒
        .and().csrf().disable();
    }
}
